package com.mqb.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

import static com.mqb.n2.util.Sleeper.sleep;

/**
 * @author mqb
 * @date 2021/5/2 20:06
 */
@Slf4j(topic = "c.TestTimer")
public class TestTimer {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        log.debug("start...");
//        pool.scheduleAtFixedRate(() -> {
//            log.debug("running...");
//            sleep(2);
//        }, 1, 1, TimeUnit.SECONDS);

/*        pool.scheduleWithFixedDelay(() -> {
            log.debug("running");
            try {
                int i = 1/0;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 1, 1, TimeUnit.SECONDS);*/

        ExecutorService pool = Executors.newFixedThreadPool(1);
        Future<Boolean> task1 = pool.submit(() -> {
            log.debug("task1");
            int i = 1 / 0;
            return true;
        });

        log.debug("result:{}",task1.get());

    }

    private static void testShceduled() {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        log.debug("start..");
        pool.schedule(() -> {
            log.debug("task1");
            //sleep(2);
            int i = 1 / 0;
        }, 1, TimeUnit.SECONDS);
        pool.schedule(() -> {
            log.debug("task2");
        }, 1, TimeUnit.SECONDS);
    }

    private static void testTimer() {
        Timer timer = new Timer();
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 1");
                //sleep(2);
                int i = 1 / 0;
            }
        };
        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 2");
            }
        };

        log.debug("start...");
        // 使用 timer 添加两个任务，希望它们都在 1s 后执行
        // 但由于 timer 内只有一个线程来顺序执行队列中的任务，因此『任务1』的延时，影响了『任务2』的执行
        timer.schedule(task1, 1000);
        timer.schedule(task2, 1000);
    }
}